from sanic import Sanic, Blueprint
from sanic.response import json
# serializer
from functools import wraps
from inspect import isawaitable
from sanic_session import Session, InMemorySessionInterface
from sanic_jinja2 import SanicJinja2
import records

# 获取app实例
app = Sanic.get_app()

# 配置信息
config = app.config

# session https://github.com/xen/sanic_session
session = Session(app, interface=InMemorySessionInterface())

# 模板引擎 https://github.com/lixxu/sanic-jinja2
view = SanicJinja2(app, session=session, pkg_path='./view')
# 注解 模板
tpl = view.template

# https://github.com/kennethreitz/records
db = config['DB_CONN']


# 序列化
def serializer(func):
    def decorator(f):
        @wraps(f)
        async def decorated_function(*args, **kwargs):
            retval = f(*args, **kwargs)
            if isawaitable(retval):
                retval = await retval
            return func(retval)
        return decorated_function
    return decorator

# 注册蓝图
def route(url, prefix='/'):
    name = url.split('.')[-1]
    if name == 'index':
        prefix = '/'
    else:
        prefix = '/'+name
    return Blueprint(url.replace('.', '_')+name, prefix)

# 公式：（当前页-1）*每页条数，每页条数
def page(page, limit=10):
    return (page-1)*limit


